var $cpu = (function()
{

var $ = function(id){ return (typeof id=='string') ? document.getElementById(id) : id; };
var isUndefine = function(o) { return (typeof o == 'undefine'); };

// 数组去重复
Array.prototype.distinct = function(){
	var result=[];
	var a=[],b=[];
	for(var prop in this){
		var d = this[prop];
		if (d===a[prop]) continue; //防止循环到prototype
		if (b[d]!=1){
			a.push(d);
			b[d]=1;
		}
	}
	return a;
}

// Maxthon runtime
var mx = window.external.mxGetRuntime();


//
var mail = [];
var txt, btn;
var capturing = false;

function init()
{
	txt = $('txt');
	btn = $('btnCapture');
	btn.onclick = toggleCapture;

	// 监听消息
	mx.listen('capture', function(o){
		if (!capturing) return;

		mail = mail.concat( o ).distinct();
		if (mail.length > 0){
			mx.icon.showBadge(mail.length);
		}else{
			mx.icon.hideBadge();
		}

		txt.value = mail.join('\n');
	});
}

/*
var key = 'capture-status';

function isRunning(value)
{
	return (mx.storage.getConfig(key) == 1);
}
*/

function toggleCapture()
{
	//if ( isRunning() ){
	if ( capturing ){
		stopCapture();
	}else{
		startCapture();
	}
}

function startCapture()
{
	//mx.storage.setConfig(key, 1);
	capturing = true;
	btn.innerHTML = '捕获中...';
	mx.icon.setIconImage('run');
}

function stopCapture()
{
	//mx.storage.setConfig(key, 0);
	capturing = false;
	btn.innerHTML = '已停止捕获';
	mx.icon.setIconImage('stop');
}

function clear()
{
	mx.icon.hideBadge();
	mail = [];
	txt.value = '';
}



return {
	init: init,
	clear: clear
};

})();
